package com.alston.rest.interceptor;


import com.alston.rest.common.TokenManager;
import com.alston.rest.common.bean.BaseResponse;
import com.alston.rest.common.bean.Code;
import com.alston.rest.common.utils.StringUtils;
import com.alston.rest.model.User;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;


/**
 * JwtToken拦截器
 * @author dyzeng
 * @date 2018-05-29
 */
public class JwtTokenInterceptor implements Interceptor {

    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        //从reques中拿出token
        String token = controller.getPara("token");
        if (StringUtils.isEmpty(token)) {
			controller.renderJson(new BaseResponse(Code.ARGUMENT_ERROR,"token不能为空"));
			return;
		}
        
        //根据token从redis数据取出user对象（因为登录的时候已经将token存入redis）
        User user = TokenManager.getUser(token);
		if (user == null) {
			controller.renderJson(new BaseResponse(Code.TOKEN_INVALID,"token已经失效,请重新登录"));	
			return;
		}
		
		//校验jwt的token合法性
		if(!TokenManager.validateToken(user.getLong("userId").toString(),token)){
			controller.renderJson(new BaseResponse(Code.TOKEN_INVALID,"token已经失效,请重新登录"));	
			return;
		}
		
		controller.setAttr("user", user);
		
		inv.invoke();
    	 
    }
}
